package com.zahb.qadx.ui.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * MBaseAdapter
 * Created by zhoudawei on 2017/7/6.
 */

public abstract class MBaseAdapter<T> extends BaseAdapter {

    private Context mContext;
    private LayoutInflater mInflater;
    private int mLayoutId;
    private List<T> mList;

    protected MBaseAdapter(@NonNull Context context, @LayoutRes int layoutId) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mLayoutId = layoutId;
        this.mList = new ArrayList<>();
    }

    protected MBaseAdapter(@NonNull Context context, @LayoutRes int layoutId, @NonNull List<T> list) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mLayoutId = layoutId;
        this.mList = list;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public T getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MViewHolder holder = MViewHolder.getViewHolder(mContext, mInflater, convertView, parent, mLayoutId);
        convert(position, holder, getItem(position));
        return holder.getConvertView();
    }

    public abstract void convert(int position, MViewHolder holder, T item);

    public void clear() {
        mList.clear();
        notifyDataSetChanged();
    }

    public void remove(int position) {
        mList.remove(position);
        notifyDataSetChanged();
    }

    public void add(T item) {
        mList.add(item);
        notifyDataSetChanged();
    }

    public void add(T item, int position) {
        mList.add(position, item);
        notifyDataSetChanged();
    }

    public void replaceAll(@NonNull List<T> list) {
        mList.clear();
        mList.addAll(list);
        notifyDataSetChanged();
    }
}
